package com.hades.oauth.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.hades.oauth.domain.OauthParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * @ClassName: CallbackController
 * @Description:
 * @Author: Hades
 * @created: 2021/04/20 22:58
 * @Version:1.0
 */
@Slf4j
@Controller
@RequestMapping("/")
public class CallbackController {

    @Value("${gitee.oauth.clientid}")
    public String CLIENTID;
    @Value("${gitee.oauth.clientsecret}")
    public String CLIENTSECRET;
    @Value("${gitee.oauth.callback}")
    public String URL;


    /**
     * 此写法首次授权后 有效期内重新请求会跳过授权页面
     * 如果需每次都进入授权页面，去掉scope
     * @return
     */
    @GetMapping("/auth")
    public String giteeOauth(){
        String uuid = UUID.randomUUID().toString().replace("-","");
        String url = "https://gitee.com/oauth/authorize?response_type=code" +
                "&client_id=" + CLIENTID +
                "&redirect_uri=" + URL +
                "&state=" + uuid +
                "&scope=user_info";
        return StrUtil.format("redirect:{}", url);
    }

    @GetMapping("/callback")
    public String giteeCallback(@RequestParam("code") String code, @RequestParam("state") String state){
        String url = "https://gitee.com/oauth/token";
        OauthParam param = new OauthParam().setClient_id(CLIENTID).setClient_secret(CLIENTSECRET).setCode(code).setRedirect_uri(URL);
        String respStr = HttpUtil.createPost(url).timeout(60*1000).body(JSONObject.toJSONString(param)).execute().body();
        log.debug(respStr);
        JSONObject respObject = JSONObject.parseObject(respStr);
        String userUrl = "https://gitee.com/api/v5/user?access_token=" + respObject.get("access_token");
        String userResp = HttpUtil.createGet(userUrl).timeout(60*1000).execute().body();
        log.debug(userResp);
        return StrUtil.format("redirect:{}", "http://localhost:9090/index");
    }

}
